//
//  ComposeController.swift
//  ZMWEIBO
//
//  Created by 庄猛 on 17/1/11.
//  Copyright © 2017年 BeiSheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeController: UIViewController {
    lazy var toolView : ComposeToolBarView = {
        
    let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: ComposeToolBarView.self), owner: nil, options: nil)?.last as! ComposeToolBarView

        temp.myDelegate = self
        
        temp.frame = CGRect(x: 0, y: KScreenH - 44, width: KScreenW, height: 44)
        
        return temp
    }()
    


    lazy var textView : ComposeTextView = {
    let temp = ComposeTextView()
    temp.frame = CGRect(x: 0, y: 0, width: KScreenW, height: KScreenH)


    temp.font = UIFont.systemFont(ofSize: 16)

    temp.alwaysBounceVertical = true

    temp.keyboardDismissMode = .onDrag

    temp.delegate = self

    temp.backgroundColor = UIColor.white
        
    return temp
    }()



   lazy var keyBardVC : EmotonKeyBardVC = EmotonKeyBardVC {
    [weak self] (emotion) in
     self!.textView.insertEmoticon(emotion: emotion)


    //判断是否是删除按钮
    if !emotion.isRemoveButton {

    self!.textView.placeholder.isHidden = true
    self!.navigationItem.rightBarButtonItem?.isEnabled = true

    }


    }

      lazy var photoVC : PhotoSelectController = PhotoSelectController()


    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.yellow
        view.addSubview(textView)
        keyBardVC.view.backgroundColor = UIColor.clear


        setNav()

        setTitleView()

        setupToolBar()


        addChildViewController(keyBardVC)


    }


    override func viewWillDisappear(_ animated: Bool) {

        super.viewWillDisappear(animated)

        textView.resignFirstResponder()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
        textView.becomeFirstResponder()
    }

    private func setNav(){
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancellDidClick))


        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(composeDidClick))

        navigationItem.rightBarButtonItem?.isEnabled = false

    }

    private func setTitleView(){

        let titleView = UIView(frame: CGRect(x: 0, y: 6, width: 200, height: 44))

        let titleTextLabel = UILabel()
        titleTextLabel.text = "出租/求租信息"
        titleTextLabel.textColor = UIColor.white
        titleTextLabel.font = UIFont.boldSystemFont(ofSize: 17)
        titleTextLabel.sizeToFit()
        titleTextLabel.frame.origin.x = (200 - titleTextLabel.frame.size.width) * 0.5
        titleView.addSubview(titleTextLabel)


        let subTitleLabel = UILabel()
        subTitleLabel.text = UserViewModel.shared.username
        subTitleLabel.font = UIFont.systemFont(ofSize: 14)
        subTitleLabel.textColor = UIColor.white
        subTitleLabel.sizeToFit()
        subTitleLabel.frame.origin.x = (200 - subTitleLabel.frame.size.width) * 0.5
        subTitleLabel.frame.origin.y = titleTextLabel.frame.size.height
        titleView.addSubview(subTitleLabel)
        navigationItem.titleView = titleView
        
    }

    private func setupToolBar(){

        addChildViewController(photoVC)

        photoVC.view.frame = CGRect(x: 0, y: KScreenH, width: KScreenW, height: KScreenH)

        view.addSubview(photoVC.view)

        view.addSubview(toolView)


        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)

//        NotificationCenter.default.addObserver(self, selector: #sele, name: Notification.Name.UIKeyboardDidChangeFrame, object: <#T##Any?#>)


    }

    @objc func keyboardWillChange(notic:Notification){
        
        
        keyBardVC.collectionView.scrollToItem(at: IndexPath(item: 0, section: 1), at: .left, animated: false)
        
        
        let duration = (notic.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue ?? 0.25
        
        //        let starRect = (notic.userInfo![UIKeyboardFrameBeginUserInfoKey]! as AnyObject).cgRectValue
        
        let endRect = (notic.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
        
        
        UIView.animate(withDuration: duration) {
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
            
            self.toolView.frame.origin.y = (endRect?.origin.y)! - 44
            
        }
        
        
        
        
        
        
    }
    

    func cancellDidClick(){
        
        
       
        


      dismiss(animated: true, completion: nil)

    }

     func composeDidClick(){
        


//        SVProgressHUD.show(withStatus: "正在发送...")
        
//            SVProgressHUD.showSuccess(withStatus: "发送成功!")

            self.cancellDidClick()
        
        if photoVC.images.count > 0 {

//            NetworkTools.shared.sendStatus(text: textView.getEmoticonString(), image: photoVC.images, finished: { (objc, error) in
//
//
//                if error != nil {
//
//                    SVProgressHUD.showError(withStatus: "发送失败...")
//
//                }else{
//
//                    //通知名称常量
//                    let NotifyChatMsgRecv = NSNotification.Name(rawValue:"sendStatusSuccsec")
//
//
//                    //发送通知
//                    NotificationCenter.default.post(name:NotifyChatMsgRecv, object: nil)
//
//
            //                    SVProgressHUD.showSuccess(withStatus: "发送成功!")
//
//                    self.cancellDidClick()
//                    
//                }
//
//
//            })

        } else {


//
//            NetworkTools.shared.sendStatus(text: textView.getEmoticonString()) { (objc, error) in
//
//
//                if error != nil {
//                    
//                    QL1(error! as NSError)
//
//                    SVProgressHUD.showError(withStatus: "发送失败...")
//
//                }else{
//
//                    //通知名称常量
//                    let NotifyChatMsgRecv = NSNotification.Name(rawValue:"sendStatusSuccsec")
//
//
//                    //发送通知
//                    NotificationCenter.default.post(name:NotifyChatMsgRecv, object: nil)
//                    
//                    
//                    SVProgressHUD.showSuccess(withStatus: "发送成功!")
//                    
//                    self.cancellDidClick()
//                    
//                }
//                
//                
//                
//            }


        }


        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}


extension ComposeController:UITextViewDelegate,ToolBarViewDelegate{

    func firstBtnDidClick(){
        
        
        if  self.photoVC.view.frame.origin.y != KScreenH{
            
            
            UIView.animate(withDuration: 0.26, animations: {
                
                self.photoVC.view.frame.origin.y = KScreenH

                
            }, completion: { (_) in
                
                self.textView.becomeFirstResponder()

            })
    
        } else {
            
            textView.resignFirstResponder()
            
            UIView.animate(withDuration: 0.26) {
                
                
                self.photoVC.view.frame.origin.y = KScreenH * 0.45
                
            }
            
            
        }





    }

    func sencendBtnDidClick(){
        
        textView.resignFirstResponder()
        
        
        if textView.inputView != nil
        {
            
            textView.inputView = nil
            
        }else{
            
            
            textView.inputView = keyBardVC.bgView
        }
        
        
        textView.becomeFirstResponder()

    }

    func thirdBtnDidClick(){


    }

    func fourBtnDidClick(){




    }

    func fiveBtnDidClick(){




    }

    func textViewDidChange(_ textView: UITextView) {

        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }

}
